package com.sl.au.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Option;
import com.sl.au.entity.BusinesssellerBaseInfo;
import com.sl.au.entity.BussinessCheck;
import com.sl.au.entity.BusinessCheckDetail;
import com.sl.au.entity.BussinessInspection;
import com.sl.au.service.BusinesssellerBaseInfoService;
import com.sl.au.service.BussinessCheckService;
import com.sl.au.service.BussinessInspectionService;
import com.sl.au.service.EvaluateService;
import com.sl.au.service.OptionService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MsgHelper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 商户核检
 * 
 * @author Heguangchuan
 *
 */
@RestController
@RequestMapping(value = "/ui/bussinessCheck")
public class BussinessCheckController extends BaseController {

	@Autowired
	private BussinessCheckService bussinessCheckService;
	@Autowired
	private BussinessInspectionService bussinessInspectionService;
	@Autowired
	private BusinesssellerBaseInfoService businesssellerBaseInfoService;
	@Autowired
	private OptionService optionService;
	@Autowired
	private EvaluateService evaluateService;

	@RequestMapping("/exportToExcel")
	public void exportToExcel(@RequestParam(value = "key", required = false) String key, HttpServletResponse response) {
		List<BussinessCheck> checks = bussinessCheckService.getChecks(0, Integer.MAX_VALUE, key, null, null);
		// 第一步创建workbook
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步创建sheet
		HSSFSheet sheet = wb.createSheet("核检记录");
		// 第三步创建行row:添加表头0行
		HSSFCellStyle style = wb.createCellStyle();
		HSSFRow row = sheet.createRow(0);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 第四步创建单元格
		HSSFCell cell0 = row.createCell(0); // 第一个单元格
		cell0.setCellValue("商户名称");
		cell0.setCellStyle(style);

		HSSFCell cell1 = row.createCell(1);
		cell1.setCellValue("商户地址");
		cell1.setCellStyle(style);

		HSSFCell cell2 = row.createCell(2);
		cell2.setCellValue("经营范围");
		cell2.setCellStyle(style);

		HSSFCell cell3 = row.createCell(3);
		cell3.setCellValue("管理员");
		cell3.setCellStyle(style);

		HSSFCell cell4 = row.createCell(4);
		cell4.setCellValue("考核情况");
		cell4.setCellStyle(style);

		HSSFCell cell5 = row.createCell(5);
		cell5.setCellValue("核检人员");
		cell5.setCellStyle(style);

		HSSFCell cell6 = row.createCell(6);
		cell6.setCellValue("联系方式");
		cell6.setCellStyle(style);

		HSSFCell cell7 = row.createCell(7);
		cell7.setCellValue("考核时间");
		cell7.setCellStyle(style);

		HSSFCell cell8 = row.createCell(8);
		cell8.setCellValue("备注");
		cell8.setCellStyle(style);

		HSSFCell cell9 = row.createCell(9);
		cell9.setCellValue("整改情况");
		cell9.setCellStyle(style);

		HSSFCell cell10 = row.createCell(10);
		cell10.setCellValue("核检项");
		cell10.setCellStyle(style);

		// 写入数据
		int totalRows = checks.size();
		for (int i = 1; i <= totalRows; i++) {
			BussinessCheck bc = checks.get(i - 1);
			BusinesssellerBaseInfo b = bc.getBusinesssellerBaseInfo();
			HSSFRow r = sheet.createRow(i);
			HSSFCell c0 = r.createCell(0);
			c0.setCellValue(b.getShopName());

			HSSFCell c1 = r.createCell(1);
			c1.setCellValue(b.getShopAdress());

			HSSFCell c2 = r.createCell(2);
			c2.setCellValue(b.getManagementRange());

			HSSFCell c3 = r.createCell(3);
			c3.setCellValue(b.getManagementPerson().getName());

			HSSFCell c4 = r.createCell(4);
			c4.setCellValue(bc.getCheckCondition());

			HSSFCell c5 = r.createCell(5);
			c5.setCellValue(bc.getUser().getName());

			HSSFCell c6 = r.createCell(6);
			c6.setCellValue(bc.getUser().getContactType());

			HSSFCell c7 = r.createCell(7);
			c7.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(bc.getCheckDate()));

			HSSFCell c8 = r.createCell(8);
			c8.setCellValue(bc.getRemark());

			HSSFCell c9 = r.createCell(9);
			c9.setCellValue(bc.getRectifyCondition());

			String d = "";
			List<BusinessCheckDetail> details = bc.getDetails();
			if (details.size() > 0 && details != null) {
				for (BusinessCheckDetail bd : details) {
					d += bd.getCheckTypeInfo().getTitle();
				}
			}
			HSSFCell c10 = r.createCell(10);
			c10.setCellValue(d);
		}

		OutputStream ouputStream = null;
		String fileName = "check.xls";
		response.setHeader("Content-disposition", fileName);
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName);
		response.setHeader("Pragma", "No-cache");

		try {
			ouputStream = response.getOutputStream();
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				wb.close();
				ouputStream.close();
			} catch (Exception e) {

				e.printStackTrace();
			}

		}

	}

	@RequestMapping(value = "/listAllSellers", method = RequestMethod.GET)
	@ResponseBody
	public MsgHelper listAllSeller() {
		List<BusinesssellerBaseInfo> infos = businesssellerBaseInfoService.findAll();
		return MsgHelper.success().put("sellers", infos);
	}

	@RequestMapping("/findById/{id}")
	@ResponseBody
	public MsgHelper findById(@PathVariable("id") String id) {
		BussinessCheck info = bussinessCheckService.findById(id);
		return MsgHelper.success().put("info", info);
	}

	@RequestMapping(value = "/getProgramType", method = RequestMethod.GET)
	public Map<String, Object> getProgramType() {

		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		List<Option> btypeforzx = this.optionService.getRepository().findByGroup("签订率");
		List<Option> btypeforws = this.optionService.getRepository().findByGroup("环境卫生");
		List<Option> btypeforsr = this.optionService.getRepository().findByGroup("市容秩序");
		List<Option> btypeforwslh = this.optionService.getRepository().findByGroup("绿化美化");
		map.put("btypeforzx", btypeforzx);
		map.put("btypeforws", btypeforws);
		map.put("btypeforsr", btypeforsr);
		map.put("btypeforwslh", btypeforwslh);
		code = 1;
		map.put("code", 1);
		return map;

	}

	@RequestMapping("/pageOnPhone")
	@ResponseBody
	public MsgHelper getPageInfoOnPhone() {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (!this.DEVICE.equals(device) && !StringUtils.hasText(device)) {
		}
		List<BussinessCheck> pageInfo = bussinessCheckService.getChecks(0, 10, identify, null, null);
		return MsgHelper.success().put("pageInfo", pageInfo);
	}

	@RequestMapping("/pageByTimeOnPhone")
	@ResponseBody
	public MsgHelper pageByTimeOnPhone() {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (!this.DEVICE.equals(device) && !StringUtils.hasText(device)) {
		}
		List<BussinessInspection> pageInfo = bussinessCheckService.getChecksByTimeAndNeedCheck(0, 10, identify, null,
				null);
		/*
		 * List<BussinessInspection> pageHistoryInfo =
		 * bussinessCheckService.getChecksByHistory(0, 30, identify, null,
		 * null);
		 */
		List<BussinessCheck> pageHistoryInfo = this.bussinessCheckService.getCheckHistory(0, 10, identify,
				this.getMyAccount().getUser(), "checkDate");

		MsgHelper helper = MsgHelper.success().put("pageInfo", pageInfo);
		helper.put("pageHistoryInfo", pageHistoryInfo);
		return helper;
	}

	@RequestMapping("/checkDetailInfo")
	@ResponseBody
	public MsgHelper checkDetailInfo() {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (!this.DEVICE.equals(device) && !StringUtils.hasText(device)) {
		}
		BussinessCheck bussinessCheck = this.bussinessCheckService.getRepository().findOne(identify);
		List<BussinessInspection> recordInfo = bussinessCheckService.getInspectionByCheckId(0, 30, identify,
				"inspectDate");
		List<BusinessCheckDetail> detailInfo = this.bussinessCheckService.getCheckDetailByCheckId(0, 30, identify,
				"createTime");
		MsgHelper helper = MsgHelper.success().put("recordInfo", recordInfo);
		helper.put("detailInfo", detailInfo);
		helper.put("bussinessCheck", bussinessCheck);

		return helper;
	}

	@RequestMapping("/pageByHistoryOnPhone")
	@ResponseBody
	public MsgHelper pageByHistoryOnPhone() {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (!this.DEVICE.equals(device) && !StringUtils.hasText(device)) {
		}
		List<BussinessInspection> pageInfo = bussinessCheckService.getChecksByHistory(0, 30, identify, null, null);
		return MsgHelper.success().put("pageInfo", pageInfo);
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public MsgHelper delete(@PathVariable(value = "id") String id) {
		bussinessCheckService.deleteById(id);
		return MsgHelper.success();
	}

	/**
	 * 保存巡检信息
	 * 
	 * @param bussinessInspection
	 *            表单提交过来的数据
	 * @return 构建的json数据
	 */
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
	@ResponseBody
	public MsgHelper save(BussinessCheck bussinessCheck,
			@RequestParam(value = "bussinessId", required = true) String bussinessId) {
		// 关联非表单数据
		BusinesssellerBaseInfo info = businesssellerBaseInfoService.findByBussinessSellerId(bussinessId);
		bussinessCheck.setBusinesssellerBaseInfo(info);
		bussinessCheck.setCheckDate(new Date());
		bussinessCheck.setUser(getMyAccount().getUser());
		bussinessCheckService.save(bussinessCheck);
		return MsgHelper.success();
	}

	@RequestMapping(value = "/saveCheckAndDetailWithFile", method = RequestMethod.POST)
	public Map<String, Object> saveCheckAndDetailWithFile(MultipartHttpServletRequest requests) {
		MultipartFile file = requests.getFile("file");

		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		// 关联非表单数据
		BusinesssellerBaseInfo info = businesssellerBaseInfoService
				.findByBussinessSellerId(request.getParameter("bussinessId"));

		// 获取当前Check图片的存储路径
		String url = "";
		if (file != null && !file.isEmpty()) {
			// 注意路径的构建
			url = getUploadFilePath(this.fileUploadPath, "img/check", file);
		}

		JSONObject project = JSONObject.fromObject(request.getParameter("bussinessCheck"));
		BussinessCheck bussinessCheck = (BussinessCheck) JSONObject.toBean(project, BussinessCheck.class);
		bussinessCheck.setBusinesssellerBaseInfo(info);
		bussinessCheck.setCheckDate(new Date());
		bussinessCheck.setUser(getMyAccount().getUser());
		bussinessCheck.setPictureAddr(url);

		List<BusinessCheckDetail> dlist = new ArrayList<>();

		double points = 0;
		JSONArray businessCheckDetailList = JSONArray.fromObject(request.getParameter("businessCheckDetail"));
		for (int i = 0; i < businessCheckDetailList.size(); i++) {
			JSONObject jsonObject = businessCheckDetailList.getJSONObject(i);
			BusinessCheckDetail businessCheckDetail = (BusinessCheckDetail) JSONObject.toBean(jsonObject,
					BusinessCheckDetail.class);
			Option option = optionService.getRepository().findOne(businessCheckDetail.getCheckTypeInfo().getId());
			double optionValue = ExdeUtil.str2double(option.getValue());
			points += optionValue;
			businessCheckDetail.setCreateTime(new Date());
			businessCheckDetail.setBussinessCheck(bussinessCheck);
			file = requests.getFile(businessCheckDetail.getCheckTypeInfo().getId());

			if (file != null && !file.isEmpty()) {
				// 注意路径的构建
				url = getUploadFilePath(this.fileUploadPath, "img/checkDetail", file);
				businessCheckDetail.setPictureAdress(url);
			}
			dlist.add(businessCheckDetail);
		}
		// 更新商户分数
		evaluateService.updateEvaluate(info.getId(), points);

		List<BussinessInspection> list = this.bussinessInspectionService
				.findByIds(request.getParameter("inspectionIdList"));

		for (BussinessInspection b : list) {
			b.setCheck(bussinessCheck);
		}
		bussinessCheckService.saveAll(bussinessCheck, dlist, list);
		code = 1;
		map.put("code", code);
		return map;
	}

	@RequestMapping(value = "/saveCheckAndDetail", method = RequestMethod.POST)
	public MsgHelper saveCheckAndDetail(@RequestBody Map<String, Object> map) {
		// 关联非表单数据
		BusinesssellerBaseInfo info = businesssellerBaseInfoService
				.findByBussinessSellerId((String) map.get("bussinessId"));

		// BussinessCheck bussinessCheck =new BussinessCheck();
		/* JSONArray jlist = JSONArray.fromObject(map.get("bussinessCheck")); */
		/*
		 * Iterator<Object> it = jlist.iterator(); while (it.hasNext()) {
		 * JSONObject ob = (JSONObject) it.next();
		 * bussinessCheck.setCheckCondition(ob.getString("checkCondition"));
		 * bussinessCheck.setLatitude(ob.getDouble("latitude"));
		 * bussinessCheck.setLongitude(ob.getDouble("longitude"));
		 * bussinessCheck.setRectifyCondition(ob.getString("rectifyCondition"));
		 * bussinessCheck.setRemark(ob.getString("remark"));
		 * bussinessCheck.setPictureAddr(ob.getString("pictureAddr")); }
		 */

		JSONObject project = JSONObject.fromObject(map.get("bussinessCheck"));
		BussinessCheck bussinessCheck = (BussinessCheck) JSONObject.toBean(project, BussinessCheck.class);
		bussinessCheck.setBusinesssellerBaseInfo(info);
		bussinessCheck.setCheckDate(new Date());
		bussinessCheck.setUser(getMyAccount().getUser());
		List<BusinessCheckDetail> dlist = new ArrayList<>();

		JSONArray businessCheckDetailList = JSONArray.fromObject(map.get("businessCheckDetail"));
		for (int i = 0; i < businessCheckDetailList.size(); i++) {
			JSONObject jsonObject = businessCheckDetailList.getJSONObject(i);
			BusinessCheckDetail businessCheckDetail = (BusinessCheckDetail) JSONObject.toBean(jsonObject,
					BusinessCheckDetail.class);
			businessCheckDetail.setCreateTime(new Date());
			businessCheckDetail.setBussinessCheck(bussinessCheck);
			dlist.add(businessCheckDetail);
		}

		// BusinessCheckDetail
		// businessCheckDetail=(BusinessCheckDetail)map.get("businessCheckDetail");
		List<BussinessInspection> list = this.bussinessInspectionService
				.findByIds((String) map.get("inspectionIdList"));

		for (BussinessInspection b : list) {
			b.setCheck(bussinessCheck);
		}
		bussinessCheckService.saveAll(bussinessCheck, dlist, list);
		return MsgHelper.success();
	}

	/**
	 * 
	 * @param map
	 *            存放到页面的数据
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.GET)
	public ModelAndView saveUI(Map<String, Object> map) {

		map.put("id", "");

		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		String inspectionIdList = request.getParameter("inspectionIdList");

		if (this.DEVICE.equals(device) && StringUtils.hasText(device)) {
			ModelAndView modelAndView = new ModelAndView();
			modelAndView.setViewName("mobile/bussinessCheck/saveOrUpdateOnPhone");
			modelAndView.addObject("bussinessId", identify);
			modelAndView.addObject("inspectionIdList", inspectionIdList);
			return modelAndView;
		} else {
			return createLayoutView("bussinessCheck/saveOrUpdate");
		}
	}

	/**
	 * 
	 * @param id
	 *            到修改页面传的id
	 * @param map
	 *            存放到页面所需要的数据
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdate/{id}", method = RequestMethod.GET)
	public ModelAndView updateUI(@PathVariable("id") String id, Map<String, Object> map) {
		map.put("id", id);

		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (this.DEVICE.equals(device) && StringUtils.hasText(device)) {
			ModelAndView modelAndView = new ModelAndView();
			modelAndView.setViewName("mobile/bussinessCheck/saveOrUpdateOnPhone");
			modelAndView.addObject("bussinessId", identify);
			return modelAndView;
		} else {
			return createLayoutView("bussinessCheck/saveOrUpdate");
		}
	}

	/**
	 * 初始化分页数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/page", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		List<BussinessCheck> checks = null;
		int count = 0;
		String device = request.getParameter("device");
		String url = request.getParameter("url");
		String identify = request.getParameter("identify");
		if (StringUtils.hasText(device) && this.DEVICE.equals(device)) {
			checks = bussinessCheckService.getChecks(start, length, identify, null, null);
		} else {
			if (StringUtils.hasText(key)) {
				checks = bussinessCheckService.getChecks(start, length, key, null, null);
			} else {
				checks = bussinessCheckService.getPage(start, length, null, null, null);
			}
		}
		count = bussinessCheckService.getCount(key);
		map.put("data", checks);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 初始化页面
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {

		String device = request.getParameter("device");
		String url = request.getParameter("url");
		String identify = request.getParameter("identify");
		// 移动端
		if (StringUtils.hasText(device) && this.DEVICE.equals(device)) {
			// 移动端访问的首页
			modelAndView.setViewName("mobile/bussinessCheck/indexOnPhone");
			modelAndView.addObject("bussinessId", identify);
			modelAndView.addObject("device", device);
			modelAndView.addObject("url", url);
		} else {
			// PC端
			modelAndView = createLayoutView("bussinessCheck/bussinessCheck");
		}
		return modelAndView;
	}

}
